// pages/mine_userinfo/index.js
// import {getChina} from '../../../utils/region.js'
const getChina = require('../../../utils/region.js').getChina;
const api = require('../../../utils/api.js').apis;
// console.log(getChina('Shenzhen'))
const toDate = require('../../../utils/tool').toDate;
const oss = require('../../../utils/oss.js')
const mWx = require('../../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: '',
    datas: '',
    nameis: false,
    hiddenis: false,
    name: '',
    introduceis: false,
    introduce: '',
    sexindex: 2,
    ageindex: 2,
    age: [],
    array: ['女', '男', '保密'],
    user: {
      index: 3,
      nickName: '',
      gender: 1,
      language: '',
      province: '',
      userImgSrc: '',
      array: '',
      introduce: '',
    },
    region: '',
    time: '',
  },
  doSearch(e) {
    this.bindnamegood()
  },
  bindint(e) {
    console.log(e)
    this.setData({
      introduce: e.detail.value
    })
  },
  bindinput(e) {
    console.log(e.detail.value, this.data.name)
    this.setData({
      name: e.detail.value
    })

  },
  // 名字确定事件
  bindnamegood() {
    console.log(this.data.name)
    if (this.data.name) {
      this.setData({
        nameis: false,
        hiddenis: false,
        'user.username': this.data.name
      })
    } else {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
    }
  },
  // 介绍确定事件
  bindnamegoods() {
    if (this.data.introduce) {
      this.setData({
        introduceis: false,
        hiddenis: false,
        'user.introduce': this.data.introduce
      })
    } else {
      this.setData({
        introduceis: false,
        hiddenis: false
      })
      // wx.showToast({
      //   title: '内容不能为空',
      //   icon: 'none'
      // })
    }
  },
  // 名字取消事件
  bindnameis() {
    console.log(this.data.introduce)

    this.setData({
      nameis: false,
      introduceis: false,
      hiddenis: false
    })


  },
  // 名字事件
  bindName() {
    this.setData({
      nameis: true,
      hiddenis: true
    })
  },
  // 名字事件
  bindintroduceis() {
    this.setData({
      introduceis: true,
      hiddenis: true
    })
  },
  // 生日选择
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  // 年龄选择
  bindPicAge(e) {
    this.setData({
      ageindex: e.detail.value
    })
  },
  // 性别选择
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var array = this.data.array[e.detail.value]
    this.setData({
      sexindex: e.detail.value,
      'user.array': array
    })
    console.log(this.data.user)
  },
  // 地区选择
  bindRegionChange(e) {
    this.setData({
      'user.address': e.detail.value[0] + e.detail.value[1] + e.detail.value[2]
    })
    console.log('地区', this.data.user.address)
  },
  // 图片上传未写完

  changeAvatar: function () {
    var that = this;
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        api.getStsOss({}).then(res => {
          // resolve(res)
          console.log(res)
          if (res.success) {
            // console.log(res.dadta.success)
            that.upLoadFileService(tempFilePaths, res.data)
          }
        })
        that.queryOssData().then(res => {
          console.log(res)

        })
      }
    });
  },
  // 更改图片路径
  upLoadFileService(file, ossData) {
    console.log(file, ossData)
    var arrurl = []
    const that = this;
    const date = new Date()
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let obj = oss.util.aliOssParams(ossData.tempAk, ossData.tempSk, 'https://xuedaozaixain.oss-cn-beijing.aliyuncs.com');
    let alikey = `user/${year}${month}${day}/user_head_${date.getTime()}_${Math.round(Math.random() * 100)}.${file[0].split('.').pop()}`;
    console.log(obj, alikey, ossData, file)
    wx.uploadFile({
      url: 'https://xuedaozaixain.oss-cn-beijing.aliyuncs.com',
      filePath: file[0],
      name: 'file',
      formData: {
        key: alikey,
        name: file[0],
        policy: obj.policy,
        OSSAccessKeyId: ossData.tempAk,
        success_action_status: '200',
        signature: obj.signature,
        'x-oss-security-token': ossData.token
      },
      success: (res) => {
        console.log("https://xuedaozaixain.oss-cn-beijing.aliyuncs.com" + "/" + alikey)

        that.setData({
          'user.userImgSrc': 'https://xuedaozaixain.oss-cn-beijing.aliyuncs.com' + "/" + alikey
        })
      },
      fail: function (res) {
        wx.showToast({
          title: JSON.stringify(res),
          icon: 'none'
        })
        // wx.hideToast();
        // wx.showModal({
        //   title: '错误提示',
        //   content: '上传图片失败',
        //   showCancel: false,
        //   success: function(res) {}
        // })
      }
    });
  },
  // 获取oss
  queryOssData() {
    return new Promise((resolve, reject) => {
      console.log(resolve)
      api.getStsOss({}).then(res => {
        // resolve(res)
        console.log(res)
      })
      // mWx.request({
      //   url: getStsOss,
      //   success: (res) => {
      //     resolve(res)
      //   }
      // })
    })
  },
  // 获取用户登录信息
  getuserInfo() {
    wx.showLoading({
      title: '加载中',
    })
    var token = wx.getStorageSync('Xd_Token')
    api.getuserInfo({
      token: token
    }).then(res => {
      var _this = this

      console.log(res.data)
      if (res.data.sex == '男') {
        _this.setData({
          sexindex: 1
        })
      } else if (res.data.sex == '女') {
        _this.setData({
          sexindex: 0
        })
      } else {
        _this.setData({
          sexindex: 2
        })
      }
      var birthday = res.data.birthday
      let arr;
      if (birthday) {
        arr = birthday.split(/[\s\n]/)
      }
      console.log(arr)
      this.setData({
        user: res.data,
        time: arr ? arr[0] : '',
        'user.address': res.data.address ? res.data.address : '未知'
      })
      wx.hideLoading()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var openId = wx.getStorageSync('openId')
    if (this.data.user.introduce == null) {
      this.setData({
        'user.introduce': ''
      })
    }
    this.getuserInfo()
    var data = new Date()
    var datas = toDate(data, 3)
    // console.log(datas)
    var arr = []
    for (let i = 1; i < 100; i++) {
      arr.push(i)
      // console.log(arr)
    }
    // 获取微信登录后本地个人信息
    var user = wx.getStorageSync('userInfo')
    console.log(user)
    // var region = getChina(user.province)
    this.setData({
      user: user,
      // region:region,
      age: arr,
      datas: datas,
      openId: openId
    })
    // getChina()

    // console.log(getChina('Shenzhen'))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let userInfo = wx.getStorageSync('userInfo');
    userInfo.perfectStatus = 'complete';
    wx.setStorageSync('userInfo', userInfo)
    console.log(11, this.data)
    api.remuserInfo({
      username: this.data.user.username,
      address: this.data.user.address,
      userImgSrc: this.data.user.userImgSrc,
      sex: this.data.user.array,
      birthday: this.data.time,
      openId: this.data.openId
    }).then(res => {
      console.log(res)
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})